package com.campusflea.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.campusflea.DateBase.UserInfo;
import com.campusflea.R;
import com.campusflea.person.Person_Godown;
import com.campusflea.person.Person_about;
import com.campusflea.person.Person_donate;
import com.campusflea.person.Person_gain;
import com.campusflea.person.Person_infor;
import com.campusflea.person.Person_sale;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * Created by Administrator on 2017/6/1 0001.
 */

public class FragmentMy extends Fragment implements View.OnClickListener{
    private String phone;
    private ImageView imageView;
    private TextView nickname;
    private LinearLayout start_user_profile,mine_check,mine_gain,
            my_Godown,my_sale,my_donate,mine_service,mine_about;
    private UserInfo userInfo;
    public FragmentMy(String phone){
        this.phone=phone;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.personinfor, null);
        imageView=(ImageView)rootView.findViewById(R.id.imageView);
        nickname=(TextView)rootView.findViewById(R.id.mine_name);
        start_user_profile=(LinearLayout)rootView.findViewById(R.id.start_user_profile);
        mine_gain=(LinearLayout)rootView.findViewById(R.id.mine_gain);
        my_Godown=(LinearLayout)rootView.findViewById(R.id.my_Godown);
        my_sale=(LinearLayout)rootView.findViewById(R.id.my_sale);
        my_donate=(LinearLayout)rootView.findViewById(R.id.my_donate);
        mine_about=(LinearLayout)rootView.findViewById(R.id.mine_about);
        start_user_profile.setOnClickListener(this);
        mine_gain.setOnClickListener(this);
        my_Godown.setOnClickListener(this);
        my_sale.setOnClickListener(this);
        my_donate.setOnClickListener(this);
        mine_about.setOnClickListener(this);

        Bmob.initialize(getActivity(), "36b62198745ed1900e5f1e8d55eb660d");
        initdata();
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        return rootView;
    }
    public void initdata(){

        String bql = "select * from UserInfo where phone = ?";
        BmobQuery<UserInfo> query=new BmobQuery<UserInfo>();
        query.setSQL(bql);
        query.setPreparedParams(new Object[]{phone});
        query.doSQLQuery(new SQLQueryListener<UserInfo>(){
            @Override
            public void done(BmobQueryResult<UserInfo> bmobQueryResult, BmobException e) {
                List<UserInfo> list = (List<UserInfo>) bmobQueryResult.getResults();
                if(list.size()==0){
                    Toast.makeText(getActivity(),"登录失败",Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(getActivity(),"登录成功",Toast.LENGTH_LONG).show();
                    userInfo=list.get(0);
                    nickname.setText(userInfo.getNickname().toString());
                    if(userInfo.getImage()!=null){

                        Bitmap bitmap=getHttpBitmap(userInfo.getImage().getFileUrl());
                        imageView.setImageBitmap(bitmap);
                    }
                }
            }
        });
    }
    public Bitmap getHttpBitmap(String url){
        Bitmap bitmap=null;
        URL myUrl;

        try {
            myUrl=new URL(url);
            HttpURLConnection conn=(HttpURLConnection)myUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.connect();
            InputStream is=conn.getInputStream();
            bitmap= BitmapFactory.decodeStream(is);
            bitmap=toRoundBitmap(bitmap);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //返回圆形bitmap
        return bitmap;
    }
    /**
     * 把bitmap转成圆形
     * */
    public Bitmap toRoundBitmap(Bitmap bitmap){
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int r=0;
        //取最短边做边长
        if(width<height){
            r=width;
        }else{
            r=height;
        }
        //构建一个bitmap
        Bitmap backgroundBm=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        //new一个Canvas，在backgroundBmp上画图
        Canvas canvas=new Canvas(backgroundBm);
        Paint p=new Paint();
        //设置边缘光滑，去掉锯齿
        p.setAntiAlias(true);
        RectF rect=new RectF(0, 0, r, r);
        //通过制定的rect画一个圆角矩形，当圆角X轴方向的半径等于Y轴方向的半径时，
        //且都等于r/2时，画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r/2, r/2, p);
        //设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_user_profile:
                Intent intent = new Intent(getActivity(),Person_infor.class);
                intent.putExtra("ui",userInfo);
                //Person_infor person_infor = new Person_infor();
                startActivity(intent);

                break;
//                case R.id.my_wallet:
//                    startActivity(new Intent(MainActivity.this, Person_gain.class));
//                    break;
            case R.id.my_sale:
                startActivity(new Intent(getActivity(), Person_sale.class));
                break;
            case R.id.my_donate:
                startActivity(new Intent(getActivity(), Person_donate.class));
                break;
            case R.id.my_Godown:
            //发布的商品
                Intent intent2 = new Intent(getActivity(),Person_Godown.class);
                intent2.putExtra("phone",phone);
                startActivity(intent2);
                break;
            case R.id.mine_about:
                startActivity(new Intent(getActivity(),Person_about.class));
                break;
            case R.id.mine_gain:
            //购买
                Intent intent1 = new Intent(getActivity(),Person_gain.class);
                intent1.putExtra("phone",phone);
                startActivity(intent1);
                break;
        }
    }
}
